package com.jcl.cloud.services.login.factory;

import com.jcl.cloud.services.login.constant.MarkInfo;
import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.GeckoDriverService;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.service.DriverCommandExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class WebDriverFactory extends BaseKeyedPooledObjectFactory<String, WebDriver> {
    private static Logger logger = LoggerFactory.getLogger(WebDriverFactory.class);

    @Override
    public WebDriver create(String s) throws Exception {
        WebDriver driver = null;
        try {
            driver = createDriver(s);
            logger.info(String.format("对象类型：%s   创建成功", s));
        } catch (Exception e) {
            logger.error(String.format("对象类型：%s   WebDriverFactory create Error:%s", s, e.getMessage()), e);
        }
        return driver;
    }

    @Override
    public PooledObject<WebDriver> wrap(WebDriver webDriver) {
        return new DefaultPooledObject<WebDriver>(webDriver);
    }


    @Override
    public void destroyObject(String key, PooledObject<WebDriver> p) throws Exception {
        logger.info("即将销毁的对象类型type : " + key);
        try {
            WebDriver driver = p.getObject();
            if (null != driver) {
                driver.quit();
            }
            logger.info("******destroyObject 成功******");
        } catch (Exception e) {
            logger.error(String.format("销毁对象发生异常:%s", e.getMessage()), e);
        }
    }

    @Override
    public boolean validateObject(String key, PooledObject<WebDriver> p) {
        boolean flag = false;
        try {
            WebDriver driver = p.getObject();
            driver.navigate().to("about:blank");
            logger.info("******validateObject 成功******");
            flag = true;
        } catch (Exception e) {
            logger.error("validateObject 发生异常：", e);
        }

        return flag;
    }

    @Override
    public void activateObject(String key, PooledObject<WebDriver> p) throws Exception {
        try {
            WebDriver driver = p.getObject();
            driver.navigate().to("about:blank");
            logger.info("******activateObject 成功******");
        } catch (Exception e) {
            logger.error("activateObject 发生异常：", e);
            throw e;
        }
    }

    @Override
    public void passivateObject(String key, PooledObject<WebDriver> p) throws Exception {
        try {
            WebDriver driver = p.getObject();
            driver.navigate().to("about:blank");
            logger.info("******passivateObject 成功******");
        } catch (Exception e) {
            logger.error("passivateObject 发生异常：", e);
            throw e;
        }
    }


    private WebDriver createDriver(String type) throws Exception {
        WebDriver driver = null;

        try {
            if ("FIREFOX".equals(type)) {
                FirefoxOptions firefoxOptions = new FirefoxOptions();
                String os = System.getProperty("os.name");
                logger.info("os类型为：" + os);
                boolean isLinux = os.startsWith("Windows");

                /*org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
                proxy.setHttpProxy("forward.xdaili.cn:80");
                proxy.setSslProxy("forward.xdaili.cn:80");
                DesiredCapabilities capabilities = DesiredCapabilities.firefox();
                capabilities.setCapability(CapabilityType.PROXY, proxy);*/

                if (isLinux) {
                    System.setProperty("webdriver.gecko.driver", "D:\\drivers\\geckodriver.exe");
                    System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe");
                    //firefoxOptions.addArguments("--headless");
                    //firefoxOptions.addArguments("--start-maximized");
                    firefoxOptions.addArguments("--window-size=1600,900");

                } else {
                    /*String ip = "forward.xdaili.cn";
                    int port = 80;
                    FirefoxProfile firefoxProfile = new FirefoxProfile();

                    firefoxProfile.setPreference("network.proxy.type", 1);
                    firefoxProfile.setPreference("network.proxy.http", ip);
                    firefoxProfile.setPreference("network.proxy.http_port", port);
                    firefoxProfile.setPreference("network.proxy.ssl", ip);
                    firefoxProfile.setPreference("network.proxy.ssl_port", port);*/




                    System.setProperty("webdriver.firefox.bin", "/app/browser/firefox/firefox");
                    System.setProperty("webdriver.gecko.driver", "/app/drivers/geckodriver");

                    firefoxOptions.addArguments("--headless");
                    firefoxOptions.addArguments("--disable-gpu");
                    firefoxOptions.addArguments("--no-sandbox");
                    firefoxOptions.addArguments("--window-size=1600,900");

                    //firefoxOptions.addArguments("--proxy-server=http://forward.xdaili.cn:80");
                    // firefoxOptions.setProxy(proxy);
                    //firefoxOptions.setCapability(CapabilityType.PROXY,proxy);

                    //firefoxOptions.setProfile(firefoxProfile);

                }


                /*GeckoDriverService geckoDriverService = GeckoDriverService.createDefaultService();
                int port = geckoDriverService.getUrl().getPort();*/
                driver = new FirefoxDriver(firefoxOptions);

                DriverCommandExecutor dce = (DriverCommandExecutor) ((FirefoxDriver) driver).getCommandExecutor();
                int port = dce.getAddressOfRemoteServer().getPort();
                logger.info("***************port = " + port + "**************");


            } else if ("CHROME".equals(type)) {
                ChromeOptions chromeOptions = new ChromeOptions();
                String os = System.getProperty("os.name");
                logger.info("os类型为：" + os);
                boolean isLinux = os.startsWith("Windows");
                if (isLinux) {
                    System.setProperty("webdriver.chrome.driver", "D:\\drivers\\chromedriver.exe");
                    //chromeOptions.addArguments("--headless");
                    //chromeOptions.addArguments("--start-maximized");
                    chromeOptions.addArguments("--window-size=1600,900");
                } else {
                    System.setProperty("webdriver.chrome.bin", "/app/browser/chrome/chrome");
                    System.setProperty("webdriver.chrome.driver", "/app/drivers/chromedriver");

                    chromeOptions.addArguments("--headless");
                    chromeOptions.addArguments("--disable-gpu");
                    chromeOptions.addArguments("--no-sandbox");
                    chromeOptions.addArguments("--window-size=1600,900");

                }
                ChromeDriverService service = ChromeDriverService.createDefaultService();
                int port = service.getUrl().getPort();
                driver = new ChromeDriver(service, chromeOptions);

                logger.info("***************port = " + port + "**************");


            }
        } catch (Exception e) {
            logger.error("创建WebDriver发生异常", e);
            throw e;
        }

        return driver;
    }
}
